﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;

namespace MetaSearcher
{
    [JsonObject]
    public struct JsonUserObejct
    {
        [JsonProperty]
        public Data[] data
        {
            get;
            set;
        }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public struct Data
    {
        [JsonProperty]
        public string index
        {
            get;
            set;
        }
        [JsonProperty]
        public string serviceClass
        {
            get;
            set;
        }
        [JsonProperty]
        public int[] prices
        {
            get;
            set;
        }
        [JsonProperty]
        public bool eTicketing
        {
            get;
            set;
        }
        [JsonProperty]
        public Segment[] segments
        {
            get;
            set;
        }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public struct Segment
    {
        [JsonProperty]
        public string indexSegment
        {
            get;
            set;
        }
        [JsonProperty]
        public string stopsCount
        {
            get;
            set;
        }
        [JsonProperty]
        public Flight[] flights
        {
            get;
            set;
        }


    }

    [JsonObject(MemberSerialization.OptIn)]
    public struct Flight
    {
        [JsonProperty]
        public string index
        {
            get;
            set;
        }
        [JsonProperty]
        public string time
        {
            get;
            set;
        }
        [JsonProperty]
        public string minAvailSeats
        {
            get;
            set;
        }
        [JsonProperty]
        public FlightLeg[] flightLegs
        {
            get;
            set;
        }

        [JsonProperty]
        public Stop[] stops
        {
            get;
            set;
        }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public struct Stop
    {
        [JsonProperty]
        public City city
        {
            get;
            set;
        }
        [JsonProperty]
        public string time
        {
            get;
            set;
        }
    }

    [JsonObject]
    public struct FlightLeg
    {
        [JsonProperty]
        public int flightNo
        {
            get;
            set;
        }
        [JsonProperty]
        public bool eTicketing
        {
            get;
            set;
        }
        [JsonProperty]
        public string airplane
        {
            get;
            set;
        }
        [JsonProperty]
        public string airline
        {
            get;
            set;
        }
        [JsonProperty]
        public string airlineCode
        {
            get;
            set;
        }
        [JsonProperty]
        public From from
        {
            get;
            set;
        }
        [JsonProperty]
        public To to
        {
            get;
            set;
        }

        [JsonProperty]
        public string fromDate
        {
            get;
            set;
        }
        [JsonProperty]

        public string fromTime
        {
            get;
            set;
        }
        [JsonProperty]
        [JsonConverter(typeof(IsoDateTimeConverter))]
        public DateTime toDate
        {
            get;
            set;
        }
        [JsonProperty]
        [JsonConverter(typeof(IsoDateTimeConverter))]
        public DateTime toTime
        {
            get;
            set;
        }
        [JsonProperty]
        public string flightClass
        {
            get;
            set;
        }
        [JsonProperty]
        public string fareBasis
        {
            get;
            set;
        }
        [JsonProperty]
        public int availSeats
        {
            get;
            set;
        }
        [JsonProperty]
        public string classCode
        {
            get;
            set;
        }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public struct From
    {
        [JsonProperty]
        public string code
        {
            get;
            set;
        }
        [JsonProperty]
        public string airport
        {
            get;
            set;
        }
        [JsonProperty]
        public string city
        {
            get;
            set;
        }
        [JsonProperty]
        public string country
        {
            get;
            set;
        }
        [JsonProperty]
        public string countryCode
        {
            get;
            set;
        }
        [JsonProperty]
        public string terminal
        {
            get;
            set;
        }
    }

    [JsonObject]
    public struct To
    {
        [JsonProperty]
        public string code
        {
            get;
            set;
        }
        [JsonProperty]
        public string airport
        {
            get;
            set;
        }
        [JsonProperty]
        public string city
        {
            get;
            set;
        }
        [JsonProperty]
        public string country
        {
            get;
            set;
        }
        [JsonProperty]
        public string countryCode
        {
            get;
            set;
        }
        [JsonProperty]
        public string terminal
        {
            get;
            set;
        }

    }

    [JsonObject(MemberSerialization.OptIn)]
    public struct City
    {
        [JsonProperty]
        public string code
        {
            get;
            set;
        }
        [JsonProperty]
        public string airport
        {
            get;
            set;
        }
        [JsonProperty]
        public string city
        {
            get;
            set;
        }
        [JsonProperty]
        public string countryCode
        {
            get;
            set;
        }
    }
    class ServerData
    {
        public string CommandId { get; set; }
        public string Activity { get; set; }
        public string Id { get; set; }

    }
    class Ozon
    {
        public string GetCityCode(string IATA)
        {
            System.Net.HttpWebRequest reqPOST = (HttpWebRequest)HttpWebRequest.Create(@"http://www.ozon.travel/ajax/cities.html "); //Устанавливаем URL запроса
            reqPOST.Method = "POST"; // Устанавливаем метод передачи данных в POST
            reqPOST.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; // Указываем тип контента
            String CityData = "Commander.Command=SearchAirLocation&Top=7&Word=" + IATA;
            byte[] sentData = Encoding.GetEncoding(1251).GetBytes(CityData);
            reqPOST.ContentLength = sentData.Length;
            System.IO.Stream sendStream = reqPOST.GetRequestStream(); // Также посылаем json-строку потоком в запрос
            sendStream.Write(sentData, 0, sentData.Length);
            sendStream.Close();
            System.Net.WebResponse result = reqPOST.GetResponse(); // Полу чаем ответ
            System.IO.Stream stream1 = result.GetResponseStream(); // Берем поток символов от полученного результата
            System.IO.StreamReader sr1 = new System.IO.StreamReader(stream1);
            string resultString = sr1.ReadToEnd(); // Запоминаем в строку
            resultString = resultString.Remove(0, 1);
            resultString = resultString.Remove(resultString.Length - 1, 1);
            ServerData FullCityData = new Newtonsoft.Json.JsonSerializer().Deserialize<ServerData>(new Newtonsoft.Json.JsonTextReader(new StringReader(resultString)));
            return FullCityData.Id;
        }

        public String GetOzoneData(String IATAFrom, String IATATo, String Date, String Class)
        {
            //Добавить редактор даты
            ////////////////////////

            String CityCodeFrom = this.GetCityCode(IATAFrom);
            String CityCodeTo = this.GetCityCode(IATATo);
            System.Net.HttpWebRequest reqPOST = (HttpWebRequest)HttpWebRequest.Create(@"http://www.ozon.travel/ajax/ajax-request-commander-y2.html"); //Устанавливаем URL запроса
            reqPOST.Method = "POST"; // Устанавливаем метод передачи данных в POST
            reqPOST.ContentType = "application/x-www-form-urlencoded"; // Указываем тип контента
            String OzoneData = "Commander.CommandExecutionMode=ASYNCHRONOUS&Commander.Command=SearchAirTariffsCalendar&From1=" + CityCodeFrom + "&To1=" + CityCodeTo + "&Date1=" + Date + "&ServiceClass=" + Class + "&Dlts=1&Children=0&Infants=0";
            byte[] sentData = Encoding.GetEncoding(1251).GetBytes(OzoneData);
            reqPOST.ContentLength = sentData.Length;
            System.IO.Stream sendStream = reqPOST.GetRequestStream(); // Также посылаем json-строку потоком в запрос
            sendStream.Write(sentData, 0, sentData.Length);
            sendStream.Close();
            System.Net.WebResponse result = reqPOST.GetResponse(); // Полу чаем ответ
            System.IO.Stream stream1 = result.GetResponseStream(); // Берем поток символов от полученного результата
            System.IO.StreamReader sr1 = new System.IO.StreamReader(stream1);
            string resultString = sr1.ReadToEnd(); // Запоминаем в строку
            ServerData serv = new Newtonsoft.Json.JsonSerializer().Deserialize<ServerData>(new Newtonsoft.Json.JsonTextReader(new StringReader(resultString)));

            while (serv.Activity != "DONE")
            {
                System.Threading.Thread.Sleep(2000);
                OzoneData = "Commander.CommandExecutionMode=SHOW_STATE&Commander.Command=SearchAirTariffsCalendar&Commander.CommandId=" + serv.CommandId;
                reqPOST = (HttpWebRequest)HttpWebRequest.Create(@"http://www.ozon.travel/ajax/ajax-request-commander-y2.html"); //Устанавливаем URL запроса
                reqPOST.Method = "POST"; // Устанавливаем метод передачи данных в POST
                reqPOST.ContentType = "application/x-www-form-urlencoded"; // Указываем тип контента
                sentData = Encoding.GetEncoding(1251).GetBytes(OzoneData);
                reqPOST.ContentLength = sentData.Length;
                sendStream = reqPOST.GetRequestStream(); // Также посылаем json-строку потоком в запрос
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();
                result = reqPOST.GetResponse(); // Полу чаем ответ
                stream1 = result.GetResponseStream(); // Берем поток символов от полученного результата
                sr1 = new System.IO.StreamReader(stream1);
                resultString = sr1.ReadToEnd(); // Запоминаем в строку
                serv = new Newtonsoft.Json.JsonSerializer().Deserialize<ServerData>(new Newtonsoft.Json.JsonTextReader(new StringReader(resultString)));

                Console.WriteLine(serv.Activity);
            }
            OzoneData = "Tariffs.Command=SearchAirTariffsCalendar&Tariffs.CommandExecutionMode=SHOW_STATE&Tariffs.CommandId=" + serv.CommandId;
            reqPOST = (HttpWebRequest)HttpWebRequest.Create(@"http://www.ozon.travel/ajax/avia_result_data.html"); //Устанавливаем URL запроса
            reqPOST.Method = "POST"; // Устанавливаем метод передачи данных в POST
            reqPOST.ContentType = "application/x-www-form-urlencoded"; // Указываем тип контента
            sentData = Encoding.GetEncoding(1251).GetBytes(OzoneData);
            reqPOST.ContentLength = sentData.Length;
            sendStream = reqPOST.GetRequestStream(); // Также посылаем json-строку потоком в запрос
            sendStream.Write(sentData, 0, sentData.Length);
            sendStream.Close();
            result = reqPOST.GetResponse(); // Полу чаем ответ
            stream1 = result.GetResponseStream(); // Берем поток символов от полученного результата
            sr1 = new System.IO.StreamReader(stream1);
            resultString = sr1.ReadToEnd(); // Запоминаем в строку
            return resultString;


        }

        public void OZONParse(string jsonObj, DBManipulation dbtest, string Connection, string cityFrom, string cityTo)
        {
            JsonUserObejct jUserObject = JsonConvert.DeserializeObject<JsonUserObejct>(jsonObj);

            for (int i = 0; i < jUserObject.data.Length; i++)
            {
                if (jUserObject.data[i].segments[0].stopsCount == "0")
                {

                    string aircompany = jUserObject.data[i].segments[0].flights[0].flightLegs[0].airlineCode; //код авиакомпании
                    int Code = jUserObject.data[i].segments[0].flights[0].flightLegs[0].flightNo; //рейс
                    string Class = jUserObject.data[i].segments[0].flights[0].flightLegs[0].classCode; //класс
                    int Price = jUserObject.data[i].prices[0]; //цена

                    //блок преобразования string в datatime 
                    string time = jUserObject.data[0].segments[0].flights[0].flightLegs[0].fromTime;
                    string date1 = jUserObject.data[0].segments[0].flights[0].flightLegs[0].fromDate;
                    string date = date1 + " " + time;
                    DateTime dt = Convert.ToDateTime(date); //дата вылета
                    DateTime current = DateTime.Today;
                    dbtest.insertIntoMain(Connection, "Ozon", cityFrom, cityTo, dt, dt, Price, aircompany, Class, current);
                    //конец блока
                }
            }
        }
    }
}
